home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: in1.uu.net!allegra!alice!ark
- From: ark@research.att.com (Andrew Koenig)
- Subject: Re: Does this create memory leak?...
- Message-ID: <DMxDwy.J80@research.att.com>
- Organization: AT&T Research, Murray Hill NJ
- References: <3123DF68.1677@sierra.net>
- Date: Sat, 17 Feb 1996 15:05:21 GMT
-
- In article <3123DF68.1677@sierra.net> T Colwell <snowbull@sierra.net> writes:
-
- > The code which follows seams like it would create a memory leak.
-
- It does. See below.
-
- > CAT CAT::operator=(const CAT & rhs)
- > {
- > if (this == &rhs)
- > return *this;
- > itsAge = new int;
- > itsWeight = new int;
- > *itsAge = rhs.GetAge();
- > *itsWeight = rhs.GetWeight();
- > }
-
- The indentaion is a little funny here, and you don't return a value in the
- normal case. Moreover, you don't delete the old values, which causes
- a memory leak, and you return a copy of the object, which in this case
- cannot be right because you didn't define a copy constructor. How about this:
-
- CAT& CAT::operator=(const CAT & rhs)
- {
- if (this != &rhs) {
- delete itsAge;
- delete itsWeight;
- itsAge = new int(rhs.GetAge());
- itsWeight = new int(rhs.GetWeight());
- }
- return *this;
- }
-
- Next you have to define a copy constructor, which is left as an exercise.
- --
- --Andrew Koenig
- ark@research.att.com
-